﻿using MicroBlog.Services;
using MicroBlog.ViewModels;
using Microsoft.AspNetCore.Mvc;

namespace MicroBlog.Controllers
{
    public class AccountController : Controller
    {
        private readonly IUserManager _userManager;

        public AccountController(IUserManager userManager)
        {
            _userManager = userManager;
        }

        public IActionResult Login(string returnUrl = "")
        {
            ViewBag.ReturnUrl = returnUrl;
            return View(new LoginViewModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var result = await _userManager.SignInAsync(HttpContext, model.Account, model.Password, model.RememberMe);
            if (result.Succeeded)
            {
                return RedirectToLocal(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "登录失败");
                return View(model);
            }
        }
        public async Task<ActionResult> LogOff()
        {
            HttpContext.Session.Clear();

            await _userManager.SignOutAsync(HttpContext);

            return RedirectToAction("Index", "Home");
        }
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToRoute(new
                {
                    area = "Admin",
                    controller = "Dashboard",
                    action = "Index"
                });
            }
        }
    }
}